package com.ziq.zcamp.util;

import android.text.TextUtils;

import com.blankj.utilcode.util.StringUtils;
import com.ziq.zcamp.util.digest.DigestUtils;
import com.ziq.zcamp.util.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

/**
 * 为了兼容旧的Md5Util API 存在的类
 * Created by wangwei on 18/12/2017.
 */

public class MD5UtilsCompat {

    private MD5UtilsCompat() {
        //no instance
    }

    public static String encode(String str) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        return encode(str.getBytes());
    }

    public static String encode(byte[] bytes) {
        try {
            return DigestUtils.md5Hex(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getMD5OfFile(File file) {

        InputStream in = null;
        try {
            in = new FileInputStream(file);
            return DigestUtils.md5Hex(in).toUpperCase(Locale.ENGLISH);
        } catch (Exception e) {

            return null;

        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * 获取文件流的md5值
     */
    public static String geFileInputStreamMD5(InputStream inputStream) {
        String md5 = "";
        try {
            md5 = DigestUtils.md5Hex(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(md5)) {
            return md5.trim();
        }
        return md5;
    }

    /**
     * 获取指定路径文件的MD5值
     */
    public static String getFilePathMD5(String path) throws IOException {
        FileInputStream in = null;
        try {
            in = new FileInputStream(path);
            return geFileInputStreamMD5(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    public static String getFileMD5(File file) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return geFileInputStreamMD5(fis);
        } finally {
            IOUtils.close(fis);
        }
    }


}
